var FEED_MANAGEMENT = {
    
	sz_storageType : "l",
	
    dataStorageManagement : null,
    /**
     * Collapsed Items
     */
    a_CollapsedItems :  new Object(),
    /**
     * Expanded Items
     */
    a_ExpandedItems :  new Object(),
    /**
     *  List of feed (key the title and value the rss xml)
     */
    a_feedList : new Array(),
    init : function() {
        FEED_MANAGEMENT.dataStorageManagement = new DataStorageManagement();
        FEED_MANAGEMENT.dataStorageManagement.create(FEED_MANAGEMENT.sz_storageType);
        
        jQuery("#addButton").unbind('click');
        jQuery("#addButton").bind( "click",function() {
            var sz_rssXML = jQuery("#flowURLText").val().toLowerCase();
            FEED_MANAGEMENT.addFeed(sz_rssXML);
            jQuery("#addFlowPage").dialog('close');
        });
        
        jQuery("#flowURLText").unbind('keyup');
        jQuery("#flowURLText").keyup(function(event) {
            if (event.which == 13) {
                var sz_rssXML = jQuery("#flowURLText").val().toLowerCase();
                FEED_MANAGEMENT.addFeed(sz_rssXML);
                jQuery("#addFlowPage").dialog('close');
            }
        });

        jQuery("#deleteButton").tap(function(){
            jQuery.each(FEED_MANAGEMENT.a_ExpandedItems,function(the_sz_xml,o_the_div){
                if(o_the_div != null) {
                    FEED_MANAGEMENT.removeFeed(the_sz_xml)
                    return false; // break
                }
            });
        });
        
        jQuery("#feedList").sortable({
            update: function() {  // callback when list order is changed
                jQuery("#feedList > div").each(function(id,o_elem) {
                    var o_to_store = {
                        title : jQuery(o_elem).attr("dcpn-feedTitle"),
                        feedURL : jQuery(o_elem).attr("dcpn-feedURL"),
                        position: id
                    };
                    FEED_MANAGEMENT.a_feedList[id] = o_to_store;
                })
                FEED_MANAGEMENT.dataStorageManagement.store('feedList', JSON.stringify(FEED_MANAGEMENT.a_feedList));
            }
        });
        FEED_MANAGEMENT.storeFeeds();
    },
    /**
     *  Get stored feeds from local storage
     */
    storeFeeds : function() {
        var a_Feeds = JSON.parse(FEED_MANAGEMENT.dataStorageManagement.getData("feedList"));
        FEED_MANAGEMENT.a_feedList = JSON.parse(FEED_MANAGEMENT.dataStorageManagement.getData("feedList"));
        if(a_Feeds) {
            //  Sort by position
            for(var i = 0  ; i < a_Feeds.length ; i++) {
                for(var j = 0  ; j < a_Feeds.length ; j++) {
                    if(a_Feeds[j] && a_Feeds[j] != null
                        && a_Feeds[j].position == i) {
                        FEED_MANAGEMENT.a_feedList[i] = a_Feeds[j];
                    }
                }
            }
        } else {
            FEED_MANAGEMENT.a_feedList = new Array();
        }
		FEED_MANAGEMENT.loadFeedFromFeedList();
    },
	/**
	*	Load feed without stored
	*/
	loadFeedFromFeedList : function(the_i_index) {
		if(typeof(the_i_index) == "undefined") {
			the_i_index = 0;
		}
		if(the_i_index >= FEED_MANAGEMENT.a_feedList.length) {
			return false;
		}
		
		if(FEED_MANAGEMENT.a_feedList[the_i_index] == null) {
			FEED_MANAGEMENT.loadFeedFromFeedList(the_i_index+1);
			return false;
		}
		var feed = new google.feeds.Feed(FEED_MANAGEMENT.a_feedList[the_i_index].feedURL);
            feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
            feed.load(function(result) {
                if (!result.error) {
					FEED_MANAGEMENT.addFeedContent(result.feed.title,result.feed.description,result.feed);
					FEED_MANAGEMENT.loadFeedFromFeedList(the_i_index+1);
                }
            });
	},
    addFeed : function(the_sz_rssXML,the_b_toStore) {
        
        if(the_sz_rssXML.substr(0,7)!='http://' && the_sz_rssXML.substr(0,8)!='https://') {
            the_sz_rssXML = "http://"+the_sz_rssXML;
        }

        var b_founded = false;
        //  only check if wanna store
        if(typeof(the_b_toStore) == "undefined" || the_b_toStore) {
            jQuery.each(FEED_MANAGEMENT.a_feedList,function(id,o_object){
                if(o_object != null) {
                    if(o_object.feedURL == the_sz_rssXML) {
                        b_founded = true;
                        return false; // break
                    }
                }
            });
        }
        if(!b_founded) {
            var feed = new google.feeds.Feed(the_sz_rssXML);
            feed.setResultFormat(google.feeds.Feed.JSON_FORMAT);
            feed.load(function(result) {
                if (!result.error) {
                    //  Store the data to the localstorage
                    if(typeof(the_b_toStore) == "undefined" || the_b_toStore) {
                        //  add to the list of feed
                        var o_to_store = {
                            title : result.feed.title,
                            feedURL : result.feed.feedUrl,
                            position : FEED_MANAGEMENT.a_feedList.length
                        };
                        FEED_MANAGEMENT.a_feedList[FEED_MANAGEMENT.a_feedList.length] = o_to_store;
                        FEED_MANAGEMENT.dataStorageManagement.store('feedList', JSON.stringify(FEED_MANAGEMENT.a_feedList));
                    }
                    FEED_MANAGEMENT.addFeedContent(result.feed.title,result.feed.description,result.feed);
                }
            });
        } else {
//            console.log("Feed already added");
        }
    },
    addFeedContent : function(the_sz_title, the_sz_description, the_a_feed) {
        var o_collapsible = jQuery("#feedList");
        var o_div = jQuery('<div data-role="collapsible" data-collapsed="true" data-theme="a">');
        o_div.attr("dcpn-feedTitle",the_sz_title);
        o_div.attr("dcpn-feedURL",the_a_feed.feedUrl);
        o_div.taphold(function() {
            console.log("TAP HOLD EVENT");
        });
        var a_entries = the_a_feed.entries;
        var o_h3 = jQuery("<h3>"+the_sz_title+"</h3>");
        o_div.append(o_h3);

        o_div.bind( "collapse", function(event, ui) {
            FEED_MANAGEMENT.a_CollapsedItems[the_a_feed.feedUrl] = o_div;
            FEED_MANAGEMENT.a_ExpandedItems[the_a_feed.feedUrl] = null;
            FEED_MANAGEMENT.checkExpanded();
        });
        o_div.bind( "expand", function(event, ui) {
            FEED_MANAGEMENT.a_ExpandedItems[the_a_feed.feedUrl] = o_div;
            FEED_MANAGEMENT.a_CollapsedItems[the_a_feed.feedUrl] = null;
            FEED_MANAGEMENT.checkExpanded();
        });

        var o_ul = jQuery('<ul data-role="listview">');
        jQuery.each(a_entries,function(id,entry) {
            var o_li = jQuery("<li>");
            var o_title = jQuery("<h3 class='ui-li-heading'>").html(entry.title);
            var o_description = jQuery("<p class='ui-li-desc'>").html(entry.contentSnippet);
            var o_imgThumb = jQuery("<img class='ui-li-thumb' />").attr("src",undefined)
        
            var o_a = jQuery("<a href='#readArticlePage'>");
            o_a.append(o_imgThumb);
            o_a.append(o_title);
            o_a.append(o_description);
            o_a.tap(function(){
                FEED_MANAGEMENT.showArticle(entry);
            });
            o_li.html(o_a);
            o_ul.append(o_li);
        });

        o_div.append(o_ul);
        o_collapsible.append(o_div)
        o_ul.listview();
        o_collapsible.collapsibleset('refresh');
    },
    checkExpanded : function() {
        var b_hasExpanded = false;
        jQuery.each(FEED_MANAGEMENT.a_ExpandedItems,function(the_sz_xml,o_the_div){
            if(o_the_div != null) {
                b_hasExpanded = true;
                jQuery("#deleteButton").show();
                return false; // break
            }
        });

        if(!b_hasExpanded) {
            jQuery("#deleteButton").hide();
        }
    },
    removeFeed : function(the_sz_xml) {
        var o_div = FEED_MANAGEMENT.a_ExpandedItems[the_sz_xml];
        o_div.remove();
        jQuery("#feedList").collapsibleset('refresh');

        jQuery.each(FEED_MANAGEMENT.a_feedList,function(id,o_object){
            if(o_object != null) {
                if(o_object.feedURL == the_sz_xml) {
                    delete FEED_MANAGEMENT.a_feedList[id];
                    delete FEED_MANAGEMENT.a_ExpandedItems[the_sz_xml];
                    jQuery("#deleteButton").hide();
                    return false;
                }
            }
        });
        FEED_MANAGEMENT.dataStorageManagement.store('feedList', JSON.stringify(FEED_MANAGEMENT.a_feedList));
    },
    showArticle : function(the_o_entry) {
        jQuery("#ReadFeed").html(the_o_entry.title);
        var o_div = jQuery('<div class="ui-body ui-body-c">');
        var o_header = jQuery('<div class="ui-body ui-body-c">').append(jQuery('<p style="font-weight:bold;font-size:12px">').html(the_o_entry.title));
        o_header.append(jQuery("<p style='font-size:10px'>").html(the_o_entry.publishedDate));
        var o_content = jQuery('<div class="ui-body ">').html(the_o_entry.content);
        
        o_div.append(o_header);
        o_div.append(o_content);
        jQuery("#readArticle").html(o_div.html());
    }
}